package com.runmonk.core.study.concurrent.thread_test;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Semaphore(信号量) 用来控制同时访问特定资源的线程数量，它通过协调各个线程以保证合理的使用公共资源
 */

public class SemaphoreTest {
    private static final int THREAD_COUNT = 30;

    //创建一个固定数量的线程池
    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

    //创建一个数量为10的信号量
    private static Semaphore semaphore = new Semaphore(10);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++){
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();//获取许可证
                        System.out.println("测试信号量。。。。。");
                        semaphore.release();//释放许可证

                        System.out.println("int getQueueLength() 返回正在等待获取许可证的线程数--->>>"+semaphore.getQueueLength());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            });
        }
    }


}
